<?php
namespace App\Http\Controllers;

use App\Http\Controllers;
use App\Repositories\TaobaoOrderRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TaobaoOrderController  extends BaseController
{
    protected $repository;

    public function __construct(TaobaoOrderRepository $repository)
    {
        $this->repository = $repository;
    }

    /**
     * 获取并处理淘宝客订单
     */
    public function fetchOrders(Request $request)
    {
        // 获取用户授权session（实际项目中应从数据库获取）
        $session = Auth::user()->taobao_session;
        
        // 查询最近12小时的订单
        $response = $this->repository->getScOrders(
            startTime: now()->subHours(12)->format('Y-m-d H:i:s'),
            endTime: now()->format('Y-m-d H:i:s'),
            queryType: 1, // 按创建时间查询
            session: $session,
            tkStatus: 3   // 只查结算成功订单
        );

        // 处理并保存订单
        $savedCount = $this->repository->processAndSaveOrders($response);
        
        // 检查是否有更多数据
        $hasMore = $response['has_next'] ?? false;
        $positionIndex = $response['position_index'] ?? null;
        
        // 分页处理逻辑
        if ($hasMore && $positionIndex) {
            // 在实际应用中，您可能希望使用队列处理后续页面
            return response()->json([
                'message' => "已保存 {$savedCount} 条订单，还有更多数据需要处理",
                'has_more' => true,
                'position_index' => $positionIndex
            ]);
        }
        
        return response()->json([
            'message' => "成功保存 {$savedCount} 条订单",
            'has_more' => false
        ]);
    }

    /**
     * 处理分页请求
     */
    public function fetchNextPage(Request $request)
    {
        $validated = $request->validate([
            'position_index' => 'required|string',
            'start_time' => 'required|date_format:Y-m-d H:i:s',
            'end_time' => 'required|date_format:Y-m-d H:i:s',
        ]);
        
        $session = Auth::user()->taobao_session;
        
        $response = $this->repository->getScOrders(
            startTime: $validated['start_time'],
            endTime: $validated['end_time'],
            queryType: 1,
            session: $session,
            tkStatus: 3,
            positionIndex: $validated['position_index']
        );

        $savedCount = $this->repository->processAndSaveOrders($response);
        
        $hasMore = $response['has_next'] ?? false;
        $positionIndex = $response['position_index'] ?? null;
        
        return response()->json([
            'saved_count' => $savedCount,
            'has_more' => $hasMore,
            'position_index' => $positionIndex
        ]);
    }
}
